package com.lagou.edu.factory;

import com.lagou.edu.annotation.MyAutowired;
import com.lagou.edu.annotation.MyComponent;
import com.lagou.edu.annotation.MyTransactional;
import com.lagou.edu.utils.AnnotationUtils;
import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author 应癫
 * <p>
 * <p>
 * 代理对象工厂：生成代理对象的
 */
@MyComponent
public class ProxyFactory {

    @MyAutowired
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /*private ProxyFactory(){

    }

    private static ProxyFactory proxyFactory = new ProxyFactory();

    public static ProxyFactory getInstance() {
        return proxyFactory;
    }*/
    public Object getProxy(Object obj) {
        Set<Class<?>> interfaces = new LinkedHashSet<>();
        Class<?> current = obj.getClass();
        while (current != null) {
            Class<?>[] ifcs = current.getInterfaces();
            for (Class<?> ifc : ifcs) {
                    interfaces.add(ifc);
            }
            current = current.getSuperclass();
        }
        if(interfaces.isEmpty()){
             return getCglibProxy(obj);
        }else {
            return getJdkProxy(obj);
        }
    }

    /**
     * Jdk动态代理
     *
     * @param obj 委托对象
     * @return 代理对象
     */
    public Object getJdkProxy(Object obj) {

        // 获取代理对象
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Method realMethod = obj.getClass().getDeclaredMethod(method.getName(), method.getParameterTypes());
                        boolean needProxy = AnnotationUtils.isTransactionalAnnotationPresentOnMethod(realMethod)
                                || AnnotationUtils.isTransactionalAnnotationPresentOnType(obj.getClass());
                        System.out.println("methodNeedProxy: " + AnnotationUtils.isTransactionalAnnotationPresentOnMethod(realMethod));
                        System.out.println("classNeedProxy: " + AnnotationUtils.isTransactionalAnnotationPresentOnType(obj.getClass()));
                        System.out.println("needProxy: " + needProxy);
                        System.out.println(realMethod.getName());
                        System.out.println(obj.getClass());
                        System.out.println(proxy.getClass());
                        Annotation[] methodAnnotations = realMethod.getAnnotations();
                        for (Annotation annotation : methodAnnotations) {
                            System.out.println(annotation.toString());
                        }
                        if(!needProxy){
                            return method.invoke(obj, args);
                        }
                        Object result = null;

                        try {
                            // 开启事务(关闭事务的自动提交)
                            transactionManager.beginTransaction();

                            result = method.invoke(obj, args);

                            // 提交事务

                            transactionManager.commit();
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 回滚事务
                            transactionManager.rollback();

                            // 抛出异常便于上层servlet捕获
                            throw e;

                        }

                        return result;
                    }
                });

    }


    /**
     * 使用cglib动态代理生成代理对象
     *
     * @param obj 委托对象
     * @return
     */
    public Object getCglibProxy(Object obj) {
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                if(!AnnotationUtils.isTransactionalAnnotationPresentOnMethod(method)
                        && !AnnotationUtils.isTransactionalAnnotationPresentOnType(obj.getClass())){
                    return method.invoke(obj, objects);
                }
                Object result = null;
                try {
                    // 开启事务(关闭事务的自动提交)
                    transactionManager.beginTransaction();

                    result = method.invoke(obj, objects);

                    // 提交事务

                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    // 回滚事务
                    transactionManager.rollback();

                    // 抛出异常便于上层servlet捕获
                    throw e;

                }
                return result;
            }
        });
    }
}
